package com.ljq.cksp.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljq.cksp.pojo.vo.LoginUserVO;
import com.ljq.cksp.security.SecurityUser;
import com.ljq.cksp.service.UserService;
import com.ljq.cksp.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

import static com.ljq.cksp.util.JWTUtil.TOKEN_PREFIX;

/**
 * @Author:ljq
 * @Date:2020/4/23
 */
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    UserService userService;

    private AuthenticationManager authenticationManager;
    public JWTLoginFilter(AuthenticationManager authenticationManager){
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        try {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                    req.getParameter("name"),
                    req.getParameter("password"));
            return authenticationManager.authenticate(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        String role = "";
        Collection<? extends GrantedAuthority> authorities = securityUser.getAuthorities();
        for (GrantedAuthority authority : authorities){
            role = authority.getAuthority();
        }
        String token = JWTUtil.createToken(securityUser.getId(), role);

        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json; charset=utf-8");
        String tokenStr = TOKEN_PREFIX + token;

        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setId(securityUser.getId());
        loginUserVO.setRole(role);
        loginUserVO.setToken(tokenStr);
        ObjectMapper objectMapper = new ObjectMapper();
        res.getWriter().print(objectMapper.writeValueAsString(loginUserVO));
    }
}
